<template>
  <div class="add">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        :closable="false"
        title="添加商品信息"
        type="info"
        center
        show-icon
      ></el-alert>
      <el-steps
        align-center
        class="font14"
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        label-position="top"
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-tabs
          @tab-click="tabClicked"
          :before-leave="beforeTabLeave"
          v-model="activeIndex"
          :tab-position="'left'"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_number">
              <el-row class="cat_opt">
                <el-col>
                  <span>选择商品分类:&nbsp;&nbsp;&nbsp;</span>
                  <el-cascader
                    v-model="addForm.goods_cat"
                    :options="catelist"
                    :props="{
                      expandTrigger: 'hover',
                      value: 'cat_id',
                      label: 'cat_name',
                      children: 'children',
                    }"
                    @change="handleChange"
                  ></el-cascader>
                </el-col>
              </el-row>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane name="1" label="商品参数">
            <el-form-item
              :key="item.attr_id"
              v-for="item in manyTableData"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :key="index"
                  v-for="(cb, index) in item.attr_vals"
                  :label="cb"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane name="2" label="商品属性">
            <el-form-item
              :key="item.attr_id"
              v-for="item in onlyTableData"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :key="index"
                  v-for="(cb, index) in item.attr_vals"
                  :label="cb"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane name="3" label="商品图片">
            <el-upload
              action="http://timemeetyou.com:8889/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="successup"
              :on-error="errorup"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>

          <el-tab-pane name="4" label="商品内容">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button @click="addnewgood" class="btnadd" type="primary"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="predialogVisible" width="50%">
      <img class="preImg" :src="prePath" alt />
    </el-dialog>
  </div>
</template>
<script>
import _ from "lodash";
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  name: "Add",
  components: {
    quillEditor
  },
  created() {
    this.getCateList();
  },
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      addFormrules: {
        goods_name: [
          { required: true, message: "请输入商品信息！", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格！", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量！", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量！", trigger: "blur" },
        ],
      },
      catelist: [],
      manyTableData: [],
      onlyTableData: [],
      headerObj: {
        Authorization: window.localStorage.getItem("token"),
      },
      prePath: "",
      predialogVisible: false,
    };
  },
  methods: {
    getCateList() {
      // const { data: res } = await this.$http.get("categories");
      const { data: res } = this.$http.get("categories").then((res) => {// eslint-disable-line no-unused-vars
        // eslint-disable-line no-unused-vars
        //   console.log(res);
        if (res.meta.status != 200) {
          return this.$message.error("获取商品分类数据失败！ ");
        }
        this.$message.success("获取商品分类数据成功！");
        this.catelist = res.data;
        // console.log(this.catelist);
      });
    },
    handleChange() {
      if (this.addForm.goods_cat.length != 3) {
        this.addForm.goods_cat = [];
      }
      return;
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName == "0" && this.addForm.goods_cat.length != 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
      return true;
    },
    tabClicked() {
      if (this.activeIndex == "1") {
        // const { data: res } = await this.$http.get(
        //   `categories/${this.addForm.goods_cat[2]}/attributes`,
        //   {
        //     params: {
        //       sel: "many"
        //     }
        //   }
        // );
        const { data: res } = this.$http(// eslint-disable-line no-unused-vars
          // eslint-disable-line no-unused-vars
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          {
            params: {
              sel: "many",
            },
          }
        ).then((res) => {
          if (res.meta.status != 200) {
            this.$message.error("获取动态参数失败！");
          }
          this.$message.success("获取动态参数成功！");
          res.data.forEach((item) => {
            item.attr_vals =
              item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
          });
          this.manyTableData = res.data;
        });
      } else if (this.activeIndex == "2") {
        // const { data: res } = await this.$http.get(
        //   `categories/${this.addForm.goods_cat[2]}/attributes`,
        //   {
        //     params: {
        //       sel: "only"
        //     }
        //   }
        // );
        const { data: res } = this.$http(// eslint-disable-line no-unused-vars
          // eslint-disable-line no-unused-vars
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          {
            params: {
              sel: "only",
            },
          }
        ).then((res) => {
          if (res.meta.status != 200) {
            this.$message.error("获取静态属性失败！");
          }
          this.$message.success("获取静态属性成功！");
          res.data.forEach((item) => {
            item.attr_vals =
              item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
          });
          this.onlyTableData = res.data;
        });
      }
    },
    handlePreview(file) {
      this.prePath = file.response.data.url;
      // console.log(this.prePath);
      this.predialogVisible = true;
    },
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;
      const i = this.addForm.pics.findIndex((x) => {
        x.pic == filePath;
      });
      this.addForm.pics.splice(i, 1);
      this.$message.success("移除图片成功！");
    },
    successup(res) {
      this.$message.success("图片暂存成功！");
      console.log(res);
      const pic = {
        pic: res.data.tmp_path,
      };
      this.addForm.pics.push(pic);
    },
    errorup() {
      this.$message.error("图片暂存失败！");
    },
    addnewgood() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写完整必要的表单项！");
        }
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        this.manyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        this.onlyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        form.attrs = this.addForm.attrs;
        // console.log(form);

        // const{data:res}=await this.$http.post('goods',form)
        // const { data: res } =
        this.$http.post("goods", form).then((res) => {
          // eslint-disable-line no-unused-vars
          console.log(res);
          // this.$message.success(res.meta.msg);
          this.$router.push("/goods");
        });
        // console.log(res);

        //   if(res.meta.status!=201){
        //   return this.$message.error('添加商品失败！')
        // }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-steps {
  margin: 15px 0;
}
.el-step__title {
  font-size: 14px;
}
.el-cascader {
  margin-left: 5px;
  width: 300px;
}
.el-checkbox {
  margin: 0 5px 0 0;
}
.preImg {
  width: 100%;
}
.btnadd {
  margin-top: 15px;
}
</style>
